package com.applcn.core.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * mf.code.common.interceptor
 * Description: 解决跨域请求的问题
 *
 * @author st
 * @date 2018-10-07 15:29
 */
public class CrossFilter extends HttpServlet implements Filter {
    private static final long serialVersionUID = 1L;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        //设置允许跨域的配置
        httpResponse.setHeader("Access-Control-Allow-Origin", httpRequest.getHeader("Origin"));
        httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS, DELETE");
        httpResponse.setHeader("Access-Control-Max-Age", "3000");
        httpResponse.setHeader("Access-Control-Allow-Headers",
                "X-Forwarded-For, User-Agent, Origin, No-Cache, Authorization, Cookie, " +
                        "X-Requested-With, Content-Type, Content-Length, Accept, Accept-Encoding, " +
                        "Accept-Language, xhrFields, Access-Control-Allow-Headers, X-CORE-ST-TOKEN, X-Token, shop-id");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(request, httpResponse);
    }
}
